<template>
  <div class="content_class" style="height: 76vh" ref="scroll" id="scrollDiv">
    <el-tree
      :data="data"
      node-key="index"
      :default-expanded-keys="array"
      class="customer_class"
      @node-click="handleNodeClick"
    />
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted, getCurrentInstance } from "vue";
import json from "@/resource/amm.json";
import { ElLoading } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import store from "@/store/index.js";
import { setHead } from "@/utils/setHead";

const bus = getCurrentInstance().appContext.config.globalProperties.$bus;

const router = useRouter();

const route = useRoute();

const data = ref();

const scroll = ref(null);

const array = reactive([0]);

const handleNodeClick = async (data, nodeProperties, treeNode) => {
  if (nodeProperties.childNodes.length == 0) {
    //把选中的手册的章节号记录到vuex中，将来还要回显的
    store.commit("setChapter", data.index);
    const loadingInstance = ElLoading.service({
      fullscreen: true,
      text: "加载中。。。",
    });
    router.push({
      path: "/details",
      query: { label: data.label, scrollTop },
    });
    nextTick(() => {
      // Loading should be closed asynchronously
      loadingInstance.close();
    });
  }
};

let scrollTop = 0;

/**
 * 计算回到本页面时，要想进度条也回到初始状态，进度条需要滚动多少
 * @param index 上次点击章节的索引
 */

const handleScroll = (event) => {
  const length = event.target.scrollTop; // 获取滚动条距离顶部的距离
  scrollTop = length;
};

onMounted(() => {
  //监听全局事件总线
  bus.on("head", (msg) => {
    setHead(document.querySelector(".content_class"), msg, 8);
  });
  //监控进度条滚动
  const scrollDiv = document.getElementById("scrollDiv");
  scrollDiv.addEventListener("scroll", handleScroll);
  //从vuex中获取数据
  if (store.getters.getManual.index == "1-1") {
    data.value = json;
  }
  array[0] = store.getters.getChapter;
  nextTick(() => {
    if (array[0] != 0) {
      scroll.value.scrollTo({ top: route.query.scrollTop, behavior: "smooth" });
      const divElement = document.querySelector(`div[data-key="${array[0]}"]`);
      divElement.style.backgroundColor = "rgb(245, 247, 250)";
    }
  });
  store.commit("clearChapter");
});
</script>

<style>
.content_class {
  overflow: auto;
}
.customer_class {
  font-family: Arial, Helvetica, sans-serif;
}

</style>
